package com.tensquare.friend.interceptor;


import cn.hutool.core.util.StrUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by WF on 2020/10/27 10:21
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtUtil jwtUtil;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.得到请求头
        String header = request.getHeader("Authorization");
        //2.判断是否有值，再得到token
        if(StrUtil.isNotBlank(header)){
            if(header.startsWith("Bearer ")){   //是否有"Bearer "开头
                //3.从第7个字符截取到结束，得到token的值
                String token = header.substring(7);
                //4.解析jwt
                Claims claims = jwtUtil.parseJWT(token);
                //5.将claims存放到request作用域中
                if(claims != null){
                    request.setAttribute("claims",claims);
                }
            }
        }

        return true;
    }
}
